import { AndroidFilled, AppleFilled, CodeFilled, Html5Filled } from '@ant-design/icons';
import { Button, Card, Form, Select, Table, TablePaginationConfig, Tag } from 'antd';
import React, { useEffect, useState } from 'react';

import ApplicationEdit from './components/ApplicationEdit';

const { Option } = Select;

interface page {
  page_size: number;
  page_number: number;
  project_id: number;
  service_type: any;
  service_id: any;
}

interface project {
  project_id: number;
  project_name: string;
}

interface serviceInfo {
  service_id: string;
  git_repo_id: number;
  git_addr: string;
  app_comment: string;
  app_name: string;
  app_type: number;
  project_list: project[];
}

const Application = () => {
  useEffect(() => {
    getApplicationList();
    getFilterApplicationList();
  }, []);

  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [filterApplication, setFilterApplication] = useState([]);
  const [showModalVisible, setShowModalVisible] = useState(false);

  let filterData: page = {
    page_size: 10,
    page_number: 1,
    project_id: 0,
    service_type: null,
    service_id: null,
  };
  const appType: any = {
    1: {
      icon: <CodeFilled style={{ color: '#2CC1DD', fontSize: '24px' }} />,
      lable: '后端',
    },
    2: {
      icon: <Html5Filled style={{ color: '#4E8CF2', fontSize: '24px' }} />,
      lable: '前端',
    },
    3: {
      icon: <AndroidFilled style={{ color: '#5BC42C', fontSize: '24px' }} />,
      lable: 'Android',
    },
    4: {
      icon: <AppleFilled style={{ color: '#C0C0C0', fontSize: '24px' }} />,
      lable: 'Apple',
    },
  };
  const onEdit = (id: string) => {
    console.log(id);
    setShowModalVisible(true);
  };

  const changeAppType = (value: string) => {
    filterData.service_type = parseInt(value);
    getApplicationList();
  };

  const changeAppID = (value: string) => {
    filterData.service_id = value;
    getApplicationList();
  };

  function getApplicationList(): void {
    setLoading(true);
    fetch(`http://ep-api-test.ichangtou.com/v1/system/service/list`, {
      method: 'POST',
      headers: {
        Authorization:
          'eyJhbGciOiJIUzUxMiIsImlhdCI6MTYyMTMwNjQ5OSwiZXhwIjoxNjIxOTExMjk5fQ.eyJ1c2VyX2lkIjozNywibmlja25hbWUiOiLkvI3nm7znm7wt55u855u8Iiwicm9sZSI6W3siaWQiOjEsIm5hbWUiOiJBRE1JTiJ9LHsiaWQiOjQsIm5hbWUiOiJURVNUIn0seyJpZCI6MiwibmFtZSI6IkRFViJ9LHsiaWQiOjExLCJuYW1lIjoiR1VFU1QifSx7ImlkIjo2LCJuYW1lIjoiREJBIn0seyJpZCI6MywibmFtZSI6Ik9QUyJ9XX0.t0v0295FKHmbYqwAjvVQhKFsNvpvXUfOgYoR4pvGgDP4FkN-LEEFDJcyYVHsbs4-HF-E4tzctdyDzXuypBLVWg',
        'Content-Type': 'application/json;charset=UTF-8',
      },
      body: JSON.stringify(filterData),
    })
      .then((res) => res.json())
      .then((data) => {
        setTotal(data.data.total_size);
        setTableData(data.data.service_list);
        setLoading(false);
      });
  }

  function getFilterApplicationList(): void {
    let param: any = { ...filterData };
    param.page_size = null;
    setLoading(true);
    fetch(`http://ep-api-test.ichangtou.com/v1/system/service/list`, {
      method: 'POST',
      headers: {
        Authorization:
          'eyJhbGciOiJIUzUxMiIsImlhdCI6MTYyMTMwNjQ5OSwiZXhwIjoxNjIxOTExMjk5fQ.eyJ1c2VyX2lkIjozNywibmlja25hbWUiOiLkvI3nm7znm7wt55u855u8Iiwicm9sZSI6W3siaWQiOjEsIm5hbWUiOiJBRE1JTiJ9LHsiaWQiOjQsIm5hbWUiOiJURVNUIn0seyJpZCI6MiwibmFtZSI6IkRFViJ9LHsiaWQiOjExLCJuYW1lIjoiR1VFU1QifSx7ImlkIjo2LCJuYW1lIjoiREJBIn0seyJpZCI6MywibmFtZSI6Ik9QUyJ9XX0.t0v0295FKHmbYqwAjvVQhKFsNvpvXUfOgYoR4pvGgDP4FkN-LEEFDJcyYVHsbs4-HF-E4tzctdyDzXuypBLVWg',
        'Content-Type': 'application/json;charset=UTF-8',
      },
      body: JSON.stringify(param),
    })
      .then((res) => res.json())
      .then((data) => {
        setFilterApplication(data.data.service_list);
      });
  }

  const changePage = (current: number) => {
    filterData.page_number = current;
    getApplicationList();
  };

  const onShowSizeChange = (current: number, pageSize: number) => {
    setPageSize(pageSize);
    filterData.page_size = pageSize;
    filterData.page_number = current;
    getApplicationList();
  };

  const pagination: TablePaginationConfig = {
    showSizeChanger: true, //设置每页显示数据条数
    showQuickJumper: false,
    showTotal: () => `共${total}条`,
    pageSize: pageSize,
    total: total, //数据的总的条数
    onChange: (current: number) => changePage(current), //点击当前页码
    onShowSizeChange: (current: number, pageSize: number) => {
      //设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
      onShowSizeChange(current, pageSize);
    },
  };

  const renderProject = (project_list: project[]) => {
    return (
      <span>
        {project_list.map((project: project) => {
          return (
            <Tag key={project.project_id} color="blue">
              {project.project_name}
            </Tag>
          );
        })}
      </span>
    );
  };

  const renderAppType = (app_type: number) => {
    return appType[app_type].icon;
  };

  const renderAction = (record: serviceInfo) => {
    return (
      <Button type="link" onClick={() => onEdit(record.service_id)}>
        编辑
      </Button>
    );
  };

  const columns: any = [
    {
      title: 'ID',
      dataIndex: 'service_id',
      key: '1',
      width: 160,
    },
    {
      title: '应用名称',
      dataIndex: 'app_name',
      width: 200,
      ellipsis: true,
      key: '2',
    },
    {
      title: '应用类型',
      dataIndex: 'app_type',
      width: 100,
      align: 'center',
      key: '3',
      render: renderAppType,
    },
    {
      title: '仓库ID',
      dataIndex: 'git_repo_id',
      width: 100,
      align: 'center',
      key: '4',
    },
    {
      title: '描述',
      dataIndex: 'app_comment',
      width: 180,
      ellipsis: true,
      key: '5',
    },
    {
      title: '绑定项目',
      dataIndex: 'project_list',
      width: 200,
      render: renderProject,
      key: '6',
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      align: 'center',
      fixed: 'right',
      render: renderAction,
    },
  ];

  return (
    <div>
      <Card bordered={false} style={{ width: '100%', marginBottom: '20px' }}>
        <Form name="basic" layout="inline">
          <Form.Item label="应用类型" name="username">
            <Select
              style={{ width: 180 }}
              onChange={changeAppType}
              defaultValue={undefined}
              allowClear>
              {Object.keys(appType).map((key) => (
                <Option key={key} value={key}>
                  {appType[key].lable}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="应用名称" name="password">
            <Select
              style={{ width: 240 }}
              onChange={changeAppID}
              defaultValue={undefined}
              showSearch
              optionFilterProp="children"
              allowClear>
              {filterApplication.map((value: any) => (
                <Option key={value.service_id} value={value.service_id}>
                  {value.app_name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getApplicationList}>
              查询
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card bordered={false} style={{ width: '100%' }}>
        <Table
          columns={columns}
          dataSource={tableData}
          pagination={pagination}
          rowKey="service_id"
          loading={loading}
        />
      </Card>
      <ApplicationEdit showModalVisible={showModalVisible} />
    </div>
  );
};

export default Application;
